<template>
  <div class="student-system">
    <!-- 顶部导航 -->
    <div class="app-header">
      <div class="header-container">
        <div class="brand">
          <span class="logo">蔚蓝琴行</span>
          <span class="system-name">学生系统</span>
        </div>
        <div class="user-status">
          <el-button 
            v-if="!isLoggedIn" 
            type="text" 
            @click="showLoginDialog"
            class="login-btn"
          >
            <el-icon><User /></el-icon>
            <span>未登录</span>
          </el-button>
          <div v-else class="user-info">
            <el-icon><UserFilled /></el-icon>
            <span>{{ studentInfo.name }}</span>
            <el-button 
              type="text" 
              @click="handleLogout"
              class="logout-btn"
            >
              <el-icon><SwitchButton /></el-icon>
              <span>退出</span>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 未登录状态 -->
      <div v-if="!isLoggedIn" class="welcome-view">
        <div class="welcome-card">
          <h2>欢迎使用学生系统</h2>
          <p>请登录查看您的课程信息</p>
          <el-button 
            type="primary" 
            size="large"
            @click="showLoginDialog"
            class="welcome-login-btn"
          >
            <el-icon><Key /></el-icon>
            <span>立即登录</span>
          </el-button>
        </div>
      </div>

      <!-- 已登录状态 -->
      <div v-else class="dashboard">
        <!-- 数据概览 -->
        <div class="stats-overview">
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="stat-card">
                <div class="stat-icon">
                  <el-icon><Calendar /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-value">{{ stats.attendedLessons }}</div>
                  <div class="stat-label">已上课时</div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-card">
                <div class="stat-icon">
                  <el-icon><Notebook /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-value">{{ stats.totalLessons }}</div>
                  <div class="stat-label">购买课时</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 课程列表 -->
        <div class="course-list">
          <div class="section-header">
            <h3>我的课程</h3>
            <el-button type="text" @click="refreshCourses">
              <el-icon><Refresh /></el-icon>
              <span>刷新</span>
            </el-button>
          </div>
          
          <div class="course-cards">
            <div 
              v-for="course in courses" 
              :key="course.id" 
              class="course-card"
              @click="viewCourseDetail(course)"
            >
              <div class="course-header">
                <h4>{{ course.courseName }}</h4>
                <el-tag :type="getCourseStatus(course)">
                  {{ getCourseStatusText(course) }}
                </el-tag>
              </div>
              <div class="course-progress">
                <el-progress 
                  :percentage="Math.round((course.finishedLessons / course.totalLessons) * 100)" 
                  :stroke-width="8"
                  :show-text="false"
                />
                <div class="progress-text">
                  <span>已完成 {{ course.finishedLessons }}/{{ course.totalLessons }} 节</span>
                  <span class="percentage">{{ Math.round((course.finishedLessons / course.totalLessons) * 100) }}%</span>
                </div>
              </div>
              <div class="course-actions">
                <el-button 
                  type="text" 
                  @click.stop="viewCourseDetail(course)"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 登录弹窗 -->
    <el-dialog 
      v-model="loginDialogVisible" 
      title="学生登录" 
      width="450px"
      :fullscreen="isPhone"
      :close-on-click-modal="false"
      class="login-dialog"
    >
      <div class="dialog-content">
        <div class="dialog-header">
          <h3><el-icon><UserFilled /></el-icon> 学生登录</h3>
          <p>请输入您的手机号登录系统</p>
        </div>
        <div class="dialog-body">
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="phone">
              <el-input 
                v-model="loginForm.phone" 
                placeholder="请输入手机号"
                maxlength="11"
                size="large"
              >
                <template #prefix>
                  <el-icon><Iphone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="name">
              <el-input 
                v-model="loginForm.name" 
                placeholder="请输入学生姓名"
                maxlength="10"
                size="large"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="handleLogin" 
            size="large"
            class="submit-btn"
          >
            立即登录
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 课程详情弹窗 -->
    <el-dialog
      v-model="courseDetailVisible"
      :title="currentCourse?.courseName"
      width="600px"
      fullscreen
      class="course-detail-dialog"
    >
      <div class="course-detail-content" v-if="currentCourse">
        <div class="detail-header">
          <div class="course-status">
            <el-tag :type="getCourseStatus(currentCourse)">
              {{ getCourseStatusText(currentCourse) }}
            </el-tag>
            <span class="progress-text">
              已完成 {{ currentCourse.finishedLessons }}/{{ currentCourse.totalLessons }} 节
              ({{ Math.round((currentCourse.finishedLessons / currentCourse.totalLessons) * 100) }}%)
            </span>
          </div>
          <el-progress
            :percentage="Math.round((currentCourse.finishedLessons / currentCourse.totalLessons) * 100)"
            :stroke-width="10"
            :color="getProgressColor(currentCourse)"
          />
        </div>

        <div class="detail-section">
          <h4>课程信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">课程类型：</span>
              <span class="info-value">{{ formatCourseType(currentCourse.type)}}</span>
            </div>
            <div class="info-item">
              <span class="info-label">授课教师：</span>
              <span class="info-value">{{ currentCourse.teacherName || '待分配' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">上课时间：</span>
              <span class="info-value">{{ getSchoolTime(currentCourse) }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>最近上课记录</h4>
          <div class="lesson-cards">
            <el-card v-for="(lesson, index) in generateRecentLessons(currentCourse)" :key="index" class="lesson-card">
              <div class="card-item">
                <span class="label">上课时间:</span>
                <span class="value">{{ parseISODateTime(lesson.schoolTime) }}</span>
              </div>
              <div class="card-item">
                <span class="label">上课内容:</span>
                <span class="value">{{ lesson.content }}</span>
              </div>
              <div class="card-item">
                <span class="label">课后作业:</span>
                <span class="value">{{ lesson.job }}</span>
              </div>
              <div class="card-item">
                <span class="label">教师:</span>
                <span class="value">{{ lesson.teacherName }}</span>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { parseISODateTime } from '@/utils/dateUtils'
import { 
  ElMessage,
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElIcon,
  ElRow,
  ElCol,
  ElProgress,
  ElTag
} from 'element-plus'
import { 
  User,
  UserFilled,
  Key,
  Calendar,
  Notebook,
  Refresh,
  Iphone,
  SwitchButton
} from '@element-plus/icons-vue'
import {
  studentLogin,
  getStudentInfo,
  studentCourseList,
  studentCourseDetail
} from '@/api/studentSystem'
import { useRouter } from 'vue-router'
const router = useRouter()

// 登录状态
const isLoggedIn = ref(false)
const loginDialogVisible = ref(false)
const loginFormRef = ref(null)
const isPhone = ref(false)

// 登录表单
const loginForm = reactive({
  phone: '',
  name: ''
})

// 登录验证规则
const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
  ]
}

const studentId = ref(null)

// 学生信息
const studentInfo = reactive({
  name: '',
  phone: ''
})

// 处理退出
const handleLogout = () => {
  isLoggedIn.value = false
  studentInfo.name = ''
  studentInfo.phone = ''
  stats.attendedLessons = 0
  stats.totalLessons = 0
  courses.value = []
  sessionStorage.removeItem('studentInfo')
  router.push('/website')
}

// 课程统计
const stats = reactive({
  attendedLessons: 0,
  totalLessons: 0
})

// 课程列表
const courses = ref([])

// 格式化课程类型
const formatCourseType = (type) => {
  const map = {
    '1': '一对一',
    '2': '小组课',
    '3': '公开课',
    '4': '试听课'
  }
  return map[type] || type
}

// 显示登录弹窗
const showLoginDialog = () => {
  loginDialogVisible.value = true
}

// 处理登录
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    const res = await studentLogin({
      phone: loginForm.phone,
      studentName: loginForm.name
    })
    if (res.code === 200) {
      sessionStorage.setItem('studentInfo', JSON.stringify(res.data))
      isLoggedIn.value = true
      loginDialogVisible.value = false
      studentInfo.name = res.data.studentName
      studentInfo.phone = res.data.phone
      studentId.value = res.data.id
      await fetchStudentData(studentId.value)
      ElMessage.success('登录成功')
    }
  } catch (error) {
    console.log(error)
  }
}

// 获取学生数据
const fetchStudentData = async (studentId) => {
  try {
    // 获取学生信息
    const infoRes = await getStudentInfo({ studentId })
    if (infoRes.code === 200) {
      stats.attendedLessons = infoRes.data.courseFinishedSum
      stats.totalLessons = infoRes.data.courseSum
    }

    // 获取课程列表
    const courseRes = await studentCourseList({ studentId })
    if (courseRes.code === 200) {
      courses.value = courseRes.data
    }
  } catch (error) {
    ElMessage.error('获取数据失败: ' + error.message)
  }
}

// 刷新课程列表
const refreshCourses = () => {
  fetchStudentData(studentId.value)
  ElMessage.success('课程列表已刷新')
}

// 课程详情弹窗
const courseDetailVisible = ref(false)
const currentCourse = ref(null)

// 查看课程详情
const viewCourseDetail = async (course) => {
  currentCourse.value = course
  try {
    const res = await studentCourseDetail({ courseId: course.id })
    if (res.code === 200) {
      currentCourse.value.recentLessons = res.data
      courseDetailVisible.value = true
    } else {
      ElMessage.error(res.message || '获取课程详情失败')
    }
  } catch (error) {
    ElMessage.error('获取课程详情失败: ' + error.message)
  }
}

// 获取课程状态
const getCourseStatus = (course) => {
  const progress = (course.finishedLessons / course.totalLessons) * 100
  if (progress >= 80) return 'success'
  if (progress >= 50) return 'warning'
  return 'danger'
}

// 获取课程状态文本
const getCourseStatusText = (course) => {
  const progress = (course.finishedLessons / course.totalLessons) * 100
  if (progress >= 80) return '即将完成'
  if (progress >= 30) return '进行中'
  return '刚开始'
}

// 获取进度条颜色
const getProgressColor = (course) => {
  const progress = (course.finishedLessons / course.totalLessons) * 100
  if (progress >= 80) return '#67C23A'
  if (progress >= 50) return '#E6A23C'
  return '#F56C6C'
}

const getSchoolTime = (row) => {
  if(row.scheduleType == '1'){
    return row.scheduleTime
  }else{
    if(row.repeatType == '1'){
      return '每天'+row.scheduleTime
    }else{
      let week = []
      row.repeatWeekly.split(',').forEach(el => {
        if(el == '1'){
          week.push("周一")
        }
        if(el == '2'){
          week.push("周二")
        }
        if(el == '3'){
          week.push("周三")
        }
        if(el == '4'){
          week.push("周四")
        }
        if(el == '5'){
          week.push("周五")
        }
        if(el == '6'){
          week.push("周六")
        }
        if(el == '7'){
          week.push("周日")
        }
      })
      
      return `每${week.join("、")} ${row.scheduleTime}`
    }
  }
}

// 生成最近上课记录
const generateRecentLessons = (course) => {
  return course.recentLessons || []
}


onMounted(() => {
  isPhone.value = /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  if (sessionStorage.getItem('studentInfo')) {
    const studentInfoSession = JSON.parse(sessionStorage.getItem('studentInfo'))
    isLoggedIn.value = true
    studentId.value = studentInfoSession.id
    studentInfo.name = studentInfoSession.studentName
    studentInfo.phone = studentInfoSession.phone
    fetchStudentData(studentId.value) 
  }
})
</script>

<style scoped>
.student-system {
  min-height: 100vh;
  background: linear-gradient(180deg, #f6f9fc 0%, #eef2f6 100%);
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    padding: 0 16px;
  }

  .main-content {
    padding: 16px;
  }

  .welcome-card {
    padding: 32px;
  }

  .stat-card {
    padding: 16px;
  }

  .stat-icon {
    width: 48px;
    height: 48px;
    font-size: 20px;
  }

  .stat-value {
    font-size: 24px;
  }

  .stat-label {
    font-size: 12px;
  }

  .course-cards {
    grid-template-columns: 1fr;
  }

  .login-dialog {
    width: 90% !important;
  }

  .dialog-content {
    padding: 16px;
  }

  .dialog-header h3 {
    font-size: 20px;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .course-detail-dialog {
    width: 100% !important;
    margin: 0 !important;
    border-radius: 0;
  }

  .course-detail-content {
    padding: 0 16px;
  }
}

/* 顶部导航样式 */
.app-header {
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 1000;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  height: 64px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.brand {
  display: flex;
  align-items: center;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  background: linear-gradient(135deg, #4e73df 0%, #1cc88a 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  margin-right: 12px;
}

.system-name {
  font-size: 18px;
  color: #333;
}

.user-status {
  display: flex;
  align-items: center;
}

.login-btn,
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
}

.user-info {
  color: #333;
}

/* 主内容区样式 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

/* 欢迎视图样式 */
.welcome-view {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 112px);
}

.welcome-card {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 48px;
  text-align: center;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  max-width: 500px;
  width: 100%;
  border: 1px solid rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
}

.welcome-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
}

.welcome-card h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 16px;
}

.welcome-card p {
  font-size: 16px;
  color: #666;
  margin-bottom: 32px;
}

.welcome-login-btn {
  width: 200px;
  border-radius: 24px;
  padding: 12px 24px;
}

/* 仪表盘样式 */
.dashboard {
  margin-top: 24px;
}

/* 统计卡片样式 */
.stats-overview {
  margin-bottom: 62px;
}

.stat-card {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
  height: 100%;
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.03);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  background-color: rgba(78, 115, 223, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: #4e73df;
  font-size: 24px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 课程列表样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h3 {
  font-size: 20px;
  color: #333;
}

.course-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.course-card {
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.03);
  position: relative;
  overflow: hidden;
}

.course-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(to bottom, #4e73df, #1cc88a);
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.course-header h4 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.course-progress {
  margin-bottom: 16px;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
  margin-top: 8px;
}

.progress-text .percentage {
  font-weight: bold;
  color: #4e73df;
}

.course-actions {
  display: flex;
  justify-content: flex-end;
}

/* 登录弹窗样式 */
.login-dialog {
  border-radius: 16px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
}

.login-dialog .el-dialog__header {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.login-dialog .el-dialog__body {
  background: transparent;
}

.dialog-content {
  padding: 24px;
}

.dialog-header {
  text-align: center;
  margin-bottom: 24px;
}

.dialog-header h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.dialog-header p {
  font-size: 14px;
  color: #666;
}

.dialog-body {
  margin-bottom: 24px;
}

.submit-btn {
  width: 100%;
  border-radius: 24px;
  height: 48px;
  font-size: 16px;
}

/* 课程详情弹窗样式 */
.course-detail-dialog {
  border-radius: 16px;
}

.course-detail-content {
  padding: 0 20px;
}

.detail-header {
  margin-bottom: 24px;
}

.course-status {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.progress-text {
  font-size: 14px;
  color: #666;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  font-size: 16px;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
}

.info-label {
  font-weight: bold;
  color: #666;
  min-width: 80px;
}

.info-value {
  color: #333;
}

.lesson-cards {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.lesson-card {
  width: 100%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.lesson-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.card-item {
  display: flex;
  align-items: baseline;
  margin-bottom: 10px;
}

.card-item:last-child {
  margin-bottom: 0;
}

.card-item .label {
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  min-width: 80px; /* 确保标签对齐 */
}

.card-item .value {
  color: #666;
  flex-grow: 1;
  word-break: break-word; /* 确保内容换行 */
}
</style>
